<?php

namespace Admin\Models\sys;

use Admin\Models\BaseModel;
use Helpers\Main;
use Helpers\User;

class XhsysConfig extends BaseModel
{

    /**
     *
     * @var integer
     */
    public $iSCId;

    /**
     *
     * @var string
     */
    public $sConfigExplain;

    /**
     *
     * @var string
     */
    public $sConfigName;

    /**
     *
     * @var string
     */
    public $sSortName;

    /**
    *
    * @var string
    */
    public $sConfigType;
    /**
     *
     * @var integer
     */
    public $bParameterType;

    /**
     *
     * @var string
     */
    public $mConfigValue;

    /**
     *
     * @var string
     */
    public $mConfigValueNew;

    /**
     *
     * @var string
     */
    public $mRemark;

    /**
     *
     * @var integer
     */
    public $bDelete;

    /**
     *
     * @var integer
     */
    public $bStatus;
    /**
     *
     * @var integer
     */
    public $iCreateUserId;

    /**
     *
     * @var string
     */
    public $tCreateDate;

    /**
     *
     * @var integer
     */
    public $iLastModifyUserId;

    /**
     *
     * @var string
     */
    public $tLastModifyDate;
    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        $this->addBehavior(new \Phalcon\Mvc\Model\Behavior\SoftDelete(
            array(
                'field' => 'bDelete',
                'value' => 1,
            )
        ));
        $this->setSource("XHSys_Config");
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'XHSys_Config';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhsysConfig[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhsysConfig
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     *
     */
    public function beforeCreate()
    {
        $userId  = User::getId();
        $time    = date('Y-m-d H:i:s');
        $this->tCreateDate = $this->tCreateDate ?: $time;
        $this->iCreateUserId = $this->iCreateUserId ?: $userId;
        $this->tLastModifyDate = $this->tLastModifyDate ?: $time;
        $this->iLastModifyUserId = $this->iLastModifyUserId ?: $userId;
    }

    /**
    * @return bool
    */
    public function beforeUpdate()
    {
        if (property_exists($this, 'tLastModifyDate')) {
                  $this->writeAttribute('tLastModifyDate', date('Y-m-d H:i:s'));
        }
        if (property_exists($this, 'iLastModifyUserId')) {
            $this->writeAttribute('iLastModifyUserId', User::getId());
        }
        return true;
    }

    /**
     * 根据节点名，key及value，修改相应节点内容
     *
     * @param $configName
     * @param $key
     * @param $value
     * @return bool
     *
     * create by ck 20161116
     */
    public static function createArrRecord($configName, $key, $value)
    {
        $obj = self::findFirst("sConfigName = '{$configName}'");
        if (!$obj) {
            $obj = new self;
            $obj->sConfigName = $configName;
            $obj->bDelete = 0;
            $obj->bStatus = 0;
        }
        $config = [];
        if ($obj->mConfigValue) {
            $config = json_decode($obj->mConfigValue, true);
        }
        $config[$key] = $value;
        $obj->mConfigValue = json_encode($config, JSON_UNESCAPED_UNICODE);
        return $obj->save();
    }

    /**
     * 根据传入参数新建/修改对应配置信息并返回对象
     *
     * @param $realData
     * @return XhsysConfig
     *
     * create by ck 20161124
     */
    public static function createRecord($realData)
    {
        $obj = $realData['iSCId'] ? self::findFirst($realData['iSCId']) : new self;
        $obj or $obj = new self;
        $obj->sConfigExplain = $realData['sConfigExplain'];
        $obj->sConfigName    = $realData['sConfigName'];
        $obj->sSortName      = $realData['sSortName'];
        $obj->sConfigType    = $realData['type'];
        $obj->bParameterType = $realData['bParameterType'];
        $obj->mRemark        = $realData['mRemark'];
        $configValue = [];
        $configValueNew = [];
        foreach ($realData['configKey'] as $index => $key) {
            if (!$key) continue;
            $configValue[$key] = $realData['configValue'][$index];
            $data = [
                'key'=>$realData['configKey'][$index],
                'name'=>$realData['configName'][$index],
                'value'=>$realData['configValue'][$index],
                'url'=>$realData['configUrl'][$index],
            ];
            array_push($configValueNew, $data);
        }
        $obj->mConfigValue = json_encode($configValue, JSON_UNESCAPED_UNICODE);
        $obj->mConfigValueNew = json_encode($configValueNew, JSON_UNESCAPED_UNICODE);
        $obj->bDelete or $obj->bDelete = 0;
        $obj->bStatus or $obj->bStatus = 0;
        return $obj;
    }

}
